import * as query from '../services/index';

const namespace = 'systems';

export default {
  namespace,

  state: {
    data: {
      list: [],
      pagination: {},
    },
    type: 'base',
  },

  effects: {
    * fetch({ payload = { type: 'apply' } }, { select, call, put }) {
      const response = yield call(query.fetch, payload);

      const { errno, pagination = {}, data = [] } = response;

      if (!errno) {
        const results = {
          data: {
            pagination: {
              total: pagination.count,
              pageSize: pagination.size,
              current: pagination.from,
            },
            list: data,
          },
          type: payload.type || 'apply',
        }

        yield put({
          type: 'save',
          payload: results,
        });
      }
    },
    * fetchGeetest({ payload = {}, callback }, { call, put }) {
      const response = yield call(query.fetchGeetest, payload);
      if (callback) callback(response);
    },
    * add({ payload = {}, callback }, { call, put }) {
      const response = yield call(query.add, payload);
      if (callback) callback(response);
    },
    * remove({ payload = {}, callback }, { call, put }) {
      const response = yield call(query.remove, payload);
      if (callback) callback(JSON.parse(response));
    },
    * update({ payload = {}, callback }, { call, put }) {
      const response = yield call(query.update, payload);
      if (callback) callback(response);
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};